package main

import (
	"context"
	"fmt"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/joho/godotenv"
	"github.com/slrun/callcenter/configs"
	"github.com/slrun/callcenter/internal/app/api"
	"github.com/slrun/callcenter/internal/app/handler"
	"github.com/slrun/callcenter/internal/service"
	"github.com/slrun/callcenter/pkg/database"
	"github.com/slrun/callcenter/pkg/logger"
)

func main() {
	// 初始化日志系统
	log := logger.NewLogger()
	log.Info("Starting Call Center API Service...")

	// 加载环境变量
	if err := godotenv.Load(); err != nil {
		log.Warn("Warning: .env file not found, using system environment variables")
	}

	// 加载配置
	log.Info("Loading configuration...")
	cfg := configs.LoadConfig()

	// 设置Gin模式
	if cfg.Server.Environment == "production" {
		gin.SetMode(gin.ReleaseMode)
		log.Info("Gin set to Release Mode for production")
	}

	// 初始化数据库连接（非致命错误，允许服务继续运行）
	log.Info("Initializing database connections...")
	if err := database.InitDB(cfg); err != nil {
		log.Error("Warning: Failed to initialize database", "error", err)
		// 继续执行，不返回
	} else {
		log.Info("Database connection established")
	}

	// 初始化Redis连接（非致命错误，允许服务继续运行）
	if err := database.InitRedis(cfg); err != nil {
		log.Error("Warning: Failed to initialize Redis", "error", err)
		// 继续执行，不返回
	} else {
		log.Info("Redis connection established")
	}

	// 初始化MongoDB连接（非致命错误，允许服务继续运行）
	if err := database.InitMongoDB(cfg); err != nil {
		log.Error("Warning: Failed to initialize MongoDB", "error", err)
		// 继续执行，不返回
	} else {
		log.Info("MongoDB connection established")
	}

	// 创建路由
	router := gin.Default()

	// 初始化服务集合
	log.Info("Initializing services...")
	// 简化服务初始化，暂时传递nil值
	svcs, err := service.NewServices(cfg, nil, nil)
	if err != nil {
		log.Fatal("Failed to initialize services", "error", err)
		return
	}
	log.Info("Services initialized successfully")

	// 初始化处理器
	h := handler.NewHandler(cfg, svcs)

	// 注册路由
	log.Info("Registering API routes...")
	api.RegisterRoutes(router, h)
	log.Info("API routes registered successfully")

	// 健康检查路由可能已经在RegisterRoutes中注册，这里不再重复注册

	// 启动检查
	log.Info("Performing startup checks...")
	if err := performStartupChecks(svcs); err != nil {
		log.Fatal("Startup checks failed", "error", err)
		return
	}
	log.Info("Startup checks passed")

	// 创建HTTP服务器
	server := &http.Server{
		Addr:    fmt.Sprintf(":%d", cfg.Server.Port),
		Handler: router,
	}

	// 在goroutine中启动服务器
	go func() {
		log.Info("Server starting", "address", server.Addr, "version", cfg.App.Version)
		if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			log.Fatal("Failed to start server", "error", err)
		}
	}()

	// 等待中断信号以优雅关闭服务器
	quit := make(chan os.Signal, 1)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit
	log.Info("Shutting down server...")

	// 设置关闭超时时间
	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()

	// 关闭服务器
	if err := server.Shutdown(ctx); err != nil {
		log.Error("Server forced to shutdown", "error", err)
	} else {
		log.Info("Server exited gracefully")
	}

	// 关闭数据库连接
	log.Info("Closing database connections...")
	if err := database.CloseDB(); err != nil {
		log.Error("Error closing database connection", "error", err)
	}
	if err := database.CloseRedis(); err != nil {
		log.Error("Error closing Redis connection", "error", err)
	}
	if err := database.CloseMongoDB(); err != nil {
		log.Error("Error closing MongoDB connection", "error", err)
	}
	log.Info("All connections closed successfully")
}

// performStartupChecks 执行启动检查，确保所有关键服务正常运行
func performStartupChecks(svcs *service.Services) error {
	// 检查核心服务是否可用
	_, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	// 检查ACD引擎是否正常
	if svcs.ACDEngine == nil {
		return fmt.Errorf("ACD Engine is not initialized")
	}

	// 检查系统服务是否正常
	if svcs.SystemService == nil {
		return fmt.Errorf("SystemService is not initialized")
	}

	return nil
}
